/*
    kevx@09/15/2011
    
    MiniWebServer handler for HTML
*/

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <memory.h>
#include "http.h"

StaticRes _$staticRes[STATIC_RES_COUNT] = {
    {"html", "text/html"},
    {"js", "application/javascript"},
    {"css", "text/css"},
    {"jpg", "image/jpeg"},
    {"png", "image/png"},
    {"gif", "image/gif"}
};

char* queryContentType(char* ext) {
    for(int i = 0; i < STATIC_RES_COUNT; i++) {
        if(strncasecmp(_$staticRes[i].ext, ext, REQ_MAX_EXT) == 0) {
            return  _$staticRes[i].ct;
        }
    }
}

int readHtmlFile(char* uri, char* buf, size_t sz) {
    char localUri[255];
    char pureUri[255];
    memset(localUri, 0, 255*sizeof(char));
    memset(pureUri, 0, 255*sizeof(char));
    
    sscanf(uri, "%[^\?\n]", pureUri);
    sprintf(localUri, "./%s", pureUri);
    FILE* f = fopen(localUri, "rb");
    if(f == NULL)
        return 0;
    
    size_t realSz = fread(buf, 1, sz, f);
    fclose(f);
    return realSz;
}

void handleHtml(HttpReq* req, HttpResp *httpResp) {
    size_t actualSz = 0;
    char buf[RESP_MAX_CT];
    ZERO_BUF(buf, RESP_MAX_CT);
    
    strncpy(httpResp->contentLanguage, RESP_CONTENT_LANG, 20);   
    if (strncasecmp(req->method, REQ_METHOD_GET, REQ_MAX_METHOD) == 0) {
        actualSz = readHtmlFile(req->uri, httpResp->body, httpResp->bodySize);
        if (actualSz <= 0) {
	        printf("!static_resource_not_found\n");
            httpResp->status = STATUS_NOT_FOUND;
            actualSz = readHtmlFile("./404.html", httpResp->body, httpResp->bodySize);
            strncpy(httpResp->result, RESP_RESULT_404, 50);
        } else {
            sprintf(buf, RESP_CONTENT_TYPE, queryContentType(req->ext));
            httpResp->status = STATUS_OK;
            strncpy(httpResp->result, RESP_RESULT_OK, 50);
            strncpy(httpResp->contentType, buf, RESP_MAX_CT);
        }
        httpResp->bodySize = actualSz;
        return;
    }
    
    
}
